package com.hongdee.scm.outwarehouse.service.impl;

import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.car.entity.TCrmCar;
import com.hongdee.crm.car.service.ITCrmCarService;
import com.hongdee.scm.common.service.ICommonService;
import com.hongdee.scm.enterwarehouse.entity.TScmEnterWareHouse;
import com.hongdee.scm.monthlybalance.service.ITScmMonthlyBalanceService;
import com.hongdee.scm.outwarehouse.dao.ITScmOutWareHouseDao;
import com.hongdee.scm.outwarehouse.entity.TScmOutWareHouse;
import com.hongdee.scm.outwarehouse.entity.TScmSaleOutWareHouse;
import com.hongdee.scm.outwarehouse.service.ITScmOutWareHouseService;
import com.hongdee.scm.stock.dao.ITScmStockDao;
import com.hongdee.scm.stock.entity.TScmStock;
import com.hongdee.scm.util.SerialNumFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/5/16.
 */
@Service
public class TScmOutWareHouseServiceImpl implements ITScmOutWareHouseService {
    @Autowired
    private ITScmOutWareHouseDao itScmOutWareHouseDao;
    @Autowired
    private ITScmStockDao itScmStockDao;
    @Autowired
    private ICommonService iCommonService;
    @Autowired
    private ITCrmCarService crmCarService;
    @Autowired
    private ITScmMonthlyBalanceService itScmMonthlyBalanceService;
    //调拨出库
    private String tabName = "T_Scm_OutWareHouse";
    //销售出库
    private String SaleTabName = "T_Scm_Sale_Out_WareHouse";


    /**
     * 出库分页
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map page(Map data, String start, String limit, String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select * from ( select tow.id,tow.out_order_num,tow.vin,tsc.car_model,tsc.car_model_code,tow.out_time, ")
                .append("case when tow.out_status='1' then '已出库' else '未出库' end outStatus,")
                .append("case when tow.outType = '1' then '销售出库' else '调拨出库' end outType, ")
                .append("case when tow.outType = '1' then '销售出库' else tao.allocation_reason end outReason, ")
                .append("case when tow.outType = '1' then '无' else tao.aim_warehouse end aimWarehouse ")
                .append(" from T_Scm_OutWareHouse tow ")
                .append("left join t_scm_sale_order tso on tow.relation_order_num=tso.id and tow.outType='1' ")
                .append("left join t_scm_allocation_order tao on tow.relation_order_num=tao.id and tow.outType='0' ")
                .append("left join t_scm_car tsc on tow.vin=tsc.vin ");
        //公司下已出库，出库单信息
        sql.append(" where tow.company_id = ? and tow.out_status='1' ");
        params.add(TokenUtil.getCompanyId(uid));
        //创建时间起
        if (data.get("createStartDate") != null && !data.get("createStartDate").equals("")) {
            sql.append(" and tow.out_time>= ?");
            params.add(data.get("createStartDate"));
        }
        //创建时间止
        if (data.get("createStopDate") != null && !data.get("createStopDate").equals("")) {
            sql.append(" and tow.out_time<= ?");
            params.add(data.get("createStopDate"));
        }
        //出库类型
        if (data.get("outType") != null && !data.get("outType").equals("")) {
            sql.append(" and tow.outType= ?");
            params.add(data.get("outType"));
        }
        //车型
        if (data.get("carModel") != null && !data.get("carModel").equals("")) {
            sql.append(" and tsc.car_model = ? ");
            params.add(data.get("carModel"));
        }
        sql.append(" ) as temp");
        return this.itScmOutWareHouseDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 确定出库
     *
     * @param vin
     * @param type 0销售 1调拨
     * @throws Exception
     */
    @Override
    public void updateOutStatus(String vin, String type) throws Exception {
        if (vin != null && !vin.equals("")) {
            if (type != null && !type.equals("")) {
                if (type.equals("0")) {
                    //销售确认出库
                    this.itScmOutWareHouseDao.executeSQL("update " + SaleTabName + " set out_status = '1' where vin = ? ", vin);

                } else if (type.equals("1")) {
                    //调拨确认出库
                    this.itScmOutWareHouseDao.executeSQL("update " + tabName + " set out_status = '1' where vin = ? ", vin);
                    this.itScmOutWareHouseDao.executeSQL("update t_scm_car set status='3' where vin = ? ", vin);
                }
            }
            //删库存
            this.itScmOutWareHouseDao.executeSQL("delete from T_SCM_STOCK where vin = ? ", vin);
            //this.itScmOutWareHouseDao.executeSQL("update t_scm_allocation_order set allocation_status = '1' where vin ")

        } else {
            throw new Exception("未选择车辆！");
        }
    }

    /**
     * 未出库车辆
     *
     * @param type
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public List notOutWareHouse(String type, String uid) throws Exception {
        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append(" SELECT * from t_scm_car where vin in (SELECT vin from t_scm_outwarehouse where out_status='0' ");
        sql.append(" and company_id = ? ");
        params.add(TokenUtil.getCompanyId(uid));
        if (type != null && !type.equals("")) {
            sql.append(" and outType = ? ");
            params.add(type);
        }
        sql.append(" )");
        return this.itScmOutWareHouseDao.list(sql.toString(), params.toArray());
    }

    /**
     * 生成出库单
     * 销售生成出库单
     *
     * @param data
     * @param uid
     * @param type
     * @throws Exception
     */
    @Override
    public void outWareHouse(Map data, String uid, String type) throws Exception {
        TScmSaleOutWareHouse entity = new TScmSaleOutWareHouse();
        //
        // System.out.println(data.get("id"));
        if (data.get("id") != null && !data.get("id").toString().equals("")) {
            throw new Exception("不允许修改出库单");
        } else {
            //vin
            if (data.get("vin") != null && !data.get("vin").toString().equals("")) {
                entity.setVin(data.get("vin").toString());
            }
            //关联单据号
            if (data.get("relationOrderNum") != null && !data.get("relationOrderNum").toString().equals("")) {
                entity.setSaleOrderNum(data.get("relationOrderNum").toString());
                //判断销售单车辆是否出库
                if (this.itScmOutWareHouseDao.info("select * from T_Scm_Sale_Order where id = ? ", data.get("relationOrderNum")).get("saleStatus").equals("1")) {
                    throw new Exception("车辆已出库！");
                }
            }
            //出库人
            entity.setOutStaff(uid);
            //公司id
            entity.setCompanyId(TokenUtil.getCompanyId(uid));
            entity.setOutStatus("0");
            this.itScmOutWareHouseDao.saveOrUpdate(entity);
        }
        //更新销售单状态为已出库（已出库）
        if (data.get("relationOrderNum") != null && !data.get("relationOrderNum").equals("")) {
            this.itScmOutWareHouseDao.executeSQL("update T_Scm_Sale_Order set sale_status = '1' where id = ? ", data.get("relationOrderNum"));
        } else {
            throw new Exception("销售单ID为空！");
        }
        //更新出库单车辆出库状态
        if (data.get("vin") != null && !data.get("vin").equals("")) {
            this.itScmOutWareHouseDao.executeSQL("update T_Scm_Car set out_warehouse_status = '2',status = '2' where vin = ? and company_id=?", data.get("vin"),TokenUtil.getCompanyId(uid));
        } else {
            throw new Exception("未对应车辆！");
        }
    }

    /**
     * 调拨保存修改
     *
     * @param tempDate
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public void requisitionSaveOrUpdate(Map tempDate, String uid) throws Exception {
        if (tempDate.get("vin") != null && !StringUtils.isEmpty(tempDate.get("vin"))) {
            List<String> vinList = (ArrayList) tempDate.get("vin");
            for (String vin : vinList) {
                //判断调拨出库打印次数,不等于0的不生成调拨出库单
                List panamTemp = new ArrayList();
                panamTemp.add(vin);
                if (tempDate.get("relationOrderNum") != null && !StringUtils.isEmpty(tempDate.get("relationOrderNum"))) {
                    panamTemp.add(tempDate.get("relationOrderNum"));
                }
                Map tempMap = this.itScmOutWareHouseDao.info("select * from t_scm_allocation_order_detail where " +
                        " vin = ? and allocation_order_id = ? ", panamTemp.toArray());
                if (tempMap.size() > 0) {
                    if (!StringUtils.isEmpty(tempMap.get("allocationOutTime")) && !tempMap.get("allocationOutTime").toString().equals("0")) {
                        continue;
                    }
                }
                TScmOutWareHouse data = new TScmOutWareHouse();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                //id为空时则为添加
                if (data.getId() == null) {
                    //默认出库日期为当前日期
                    data.setOutDate(sdf.format(new Date()));
                    data.setCreateUser(uid);
                    data.setVin(vin);
                    if (tempDate.get("outType") != null && !StringUtils.isEmpty(tempDate.get("outType"))) {
                        data.setOutType(String.valueOf(tempDate.get("outType")));
                    } else {
                        throw new Exception("出库类型不能为空！");
                    }
                    if (tempDate.get("estimateBackDate") != null && !StringUtils.isEmpty(tempDate.get("estimateBackDate"))) {
                        data.setEstimateBackDate(String.valueOf(tempDate.get("estimateBackDate")));
                    } else {
                        throw new Exception("预计回库时间不能为空！");
                    }
                    if (tempDate.get("relationOrderNum") != null && !StringUtils.isEmpty(tempDate.get("relationOrderNum"))) {
                        data.setRelationOrderNum(String.valueOf(tempDate.get("relationOrderNum")));
                    } else {
                        throw new Exception("调拨单ID不能为空！");
                    }
                    //默认出库状态
                    data.setOutStatus("0");
                    data.setOutStaff(uid);
                    data.setCompanyId(TokenUtil.getCompanyId(uid));
                    //计算预计出库日期
                    if (!data.getEstimateBackDate().equals("")) {
                        if (!data.getOutDate().equals("")) {
                            //计算保存预计出库天数
                            Date estimeBackDate = sdf.parse(data.getEstimateBackDate());
                            Date outDate = sdf.parse(data.getOutDate());
                            if (estimeBackDate.after(outDate)||estimeBackDate.equals(outDate)) {
                                String day = String.valueOf((estimeBackDate.getTime() - outDate.getTime()) / (1000 * 3600 * 24));
                                data.setEstimateOutDay(day);
                            } else {
                                throw new Exception("预计回库时间不允许小于出库时间！");
                            }
                        } else {
                            throw new Exception("请填写出库时间！");
                        }
                    } else {
                        throw new Exception("请填写预计出库时间！");
                    }
                } else {
                    //id不为空时则为修改
                    data.setUpdateUser(uid);
                    data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
                }
                data.setCompanyId(TokenUtil.getCompanyId(uid));
                this.itScmOutWareHouseDao.saveOrUpdate(data);
                //回写出库日期，预计回库天数
                this.itScmOutWareHouseDao.executeSQL("update t_scm_allocation_order set out_warehouse_date = ? ," +
                        " estimate_out_day = ? where id = ? ", data.getOutDate(), data.getEstimateOutDay(), data.getRelationOrderNum());
                //回写车辆调拨在途状态
                this.itScmOutWareHouseDao.executeSQL("update t_scm_car set status = '3' where vin = ? ", data.getVin());
            }
        }
    }

    /**
     * 销售出库分页
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map salePage(Map data, String start, String limit, String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select p.*,tsc.car_series carSeriesName,tsc.car_model modelName,tsc.configure configureName,tsc.appearance_name,tsc.trim_name interiorName")
                .append(" from " + tabName + " p  left join t_scm_car tsc on p.vin = tsc.vin ")
                .append(" where p.company_id = ?");
        params.add(TokenUtil.getCompanyId(uid));
        //调拨出库类型
//        if(data.get("outType")!=null&&!data.get("outType").equals("")){
//            sql.append(" and out_type = ? ");
//            params.add(data.get("outType"));
//        }
        //vin
        if (data.get("vin") != null && !data.get("vin").equals("")) {
            sql.append(" and p.vin = ? ");
            params.add(data.get("vin"));
        }
        if (data.get("status") != null && !data.get("status").equals("")) {
            sql.append(" and p.out_status = ? ");
            params.add(data.get("status"));
        }
        //车系
        if (data.get("carSeriesCode") != null && !data.get("carSeriesCode").equals("")) {

            sql.append("  and tsc.car_series_id = ? ");
            params.add(data.get("carSeriesCode"));
            //车型代码
            if (data.get("carModelCode") != null && !data.get("carModelCode").equals("")) {

                sql.append(" and tsc.car_model_id = ? ");
                params.add(data.get("carModelCode"));
                //车辆配置
                if (data.get("carConfigureCode") != null && !data.get("carConfigureCode").equals("")) {

                    sql.append(" and tsc.configure_id = ?");
                    params.add(data.get("carConfigureCode"));

                }
            }
        }
        return this.itScmOutWareHouseDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 调拨出库分页
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map requisitionPage(Map data, String start, String limit, String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select tso.*, p.car_series carSeriesName,p.car_model modelName,p.configure configureName,p.appearance_name,p.trim_name interiorName" +
                ",o.allocation_date,case tso.outType when '1' then ss.warehouse when '2' then o.from_warehouse end aim_warehouse,o.allocation_reason,o.estimate_back_date" +
                " from T_Scm_OutWareHouse tso " +
                " LEFT JOIN t_scm_car p ON tso.car_id = p.id  " +
                " left join t_scm_allocation_order_detail d ON tso.vin = d.vin and d.allocation_order_id = tso.relation_order_num" +
                " left join t_scm_sale_order ss on ss.car_id=tso.car_id and  ss.status ='0'" +
                " left join t_scm_allocation_order o on o.id = d.allocation_order_id where p.company_id=? " );
        params.add(TokenUtil.getCompanyId(uid));

        //出库类型
        if (data.get("outType") != null && !StringUtils.isEmpty(data.get("outType"))) {
            sql.append(" and tso.outType = ? ");
            params.add(data.get("outType"));
        }
        //出库状态0未确认出库1已确认
        if (data.get("outStatus") != null && !StringUtils.isEmpty(data.get("outStatus"))) {
            if(data.get("outStatus").equals("0")){
                sql.append(" and tso.out_status = ? ");
            }else{
                sql.append(" and tso.out_status = ? ");
            }
            params.add(data.get("outStatus"));
            if ("1".equals(data.get("outStatus"))) ///待回库车辆
            {
                sql.append(" and need_back='0' ");
            }
        }
        //vin查询
        if (data.get("vin") != null && !StringUtils.isEmpty(data.get("vin"))) {
            sql.append(" and tso.vin like ? ");
            params.add("%"+data.get("vin")+"%");
        }
        //出库时间起止
        if (data.get("outDateStart") != null && !StringUtils.isEmpty(data.get("outDateStart"))) {
            sql.append(" and tso.out_date >= ? ");
            params.add(data.get("outDateStart"));
        }
        if (data.get("outDateStop") != null && !StringUtils.isEmpty(data.get("outDateStop"))) {
            sql.append(" and tso.out_date <= ? ");
            params.add(data.get("outDateStop"));
        }
        //车系
        if (data.get("carSeriesCode") != null && !data.get("carSeriesCode").equals("")) {
            sql.append(" and p.car_series_id = ? ");
            params.add(data.get("carSeriesCode"));
            //车型代码
            if (data.get("carModelCode") != null && !data.get("carModelCode").equals("")) {
                sql.append(" and p.car_model_id = ? ");
                params.add(data.get("carModelCode"));
                //车辆配置
                if (data.get("carConfigureCode") != null && !data.get("carConfigureCode").equals("")) {
                    sql.append(" and p.configure_id = ?");
                    params.add(data.get("carConfigureCode"));

                }
            }
        }
        return this.itScmOutWareHouseDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 准备出库
     * @param data
     * @param uid
     */
    @Override
    public void prepareOut(Map data, String uid,String type) throws Exception{

        String cid = TokenUtil.getCompanyId(uid);
        List<String> vinList = (ArrayList) data.get("vin");

        List<Map<String, Object>> list = new ArrayList<>();
        for (String vin : vinList) {
            if(vin!=null&&!vin.equals("")){ //vin不为空
                if(type.equals("1")) { //销售
                    if (this.itScmOutWareHouseDao.list("select * from t_scm_sale_order_detail where vin =? and status ='0' and company_id=?", vin, cid).size() <= 0) {
                        throw new Exception("请先匹配车辆");
                    }
                }
                //打印过的车辆不让该车辆再打印出库单 zhc20170928 这样判断不准确，需要增加关联单号过滤，先注释,在后面一并判断
                //if(this.itScmOutWareHouseDao.list("select * from t_scm_outwarehouse where vin =? and outtype='2' and out_status='0' and company_id=?",vin,cid).size()>0){
                //     throw new Exception(vin+"已在待出库列表中");
                //}
                // if(this.itScmStockDao.list("select * from T_Scm_OutWareHouse where vin = ? and out_print_date is not null and out_status <> '2' and out_status <> '-1' and company_id=?", vin,cid).size()>0){
                //   throw new Exception("车架号为"+vin+"的车辆已打印过出库单");
                // }

                //查询该车辆id是否存在出库表中,这儿也需要增加关联号查询
                list = this.itScmOutWareHouseDao.list("select * from T_Scm_OutWareHouse " +
                        "where vin=? and company_id=? and relation_order_num=? ", vin, cid, data.get("relationOrderNum").toString());

                if (null != list && list.size() > 0 )  ///存在于出库列表中，应该只有一条
                {
                    if ( "0".equals(list.get(0).get("outStatus")))
                    {
                        throw new Exception(vin+"已在待出库列表中");
                    }
                    else
                    {
                        throw new Exception("车架号为"+vin+"的车辆已打印过出库单");
                    }
                }
                else{
                    //查询该车辆id是否在库存表中
                    List stockInfoList = this.itScmStockDao.list("select * from T_Scm_Stock where vin = ? and company_id=?", vin,cid);
                    if (stockInfoList.size()<=0) {
                        throw new Exception(vin+"该车辆没有库存");
                    }

                    TScmOutWareHouse entity= new TScmOutWareHouse();

                    //车辆id
                    list = this.itScmOutWareHouseDao.list("select * from t_scm_car where vin=? and company_id=?",vin,cid);
                    Map m = new HashMap();
                    if(list.size()>0) {
                        m = (Map) list.get(0);
                    }
                    entity.setCarId(m.get("id").toString());
                    //vin
                    entity.setVin(vin);
                    Map sm = (Map) stockInfoList.get(0);
                    if(sm.get("warehouseId")!=null&&!"".equals(sm.get("warehouseId"))){
                        entity.setOutWarehouseId( sm.get("warehouseId").toString());
                    }
                    //关联单据号
                    if (data.get("relationOrderNum") != null && !data.get("relationOrderNum").toString().equals("")) {
                        entity.setRelationOrderNum(data.get("relationOrderNum").toString());
                    }
                    //出库状态（1销售出库2调拨出库）
                    if(type.equals("1")){
                        //更新销售单状态为已出库（已出库）(修改出库状态)
                        if (data.get("relationOrderNum") != null && !data.get("relationOrderNum").equals("")) {
                            //this.itScmOutWareHouseDao.executeSQL("update T_Scm_Sale_Order set sale_status = '1' where id = ? ", data.get("relationOrderNum"));
                            entity.setOutType("1");
                            entity.setNeedBack("1");
                        } else {
                            throw new Exception("销售单ID为空！");
                        }

                        entity.setEstimateOutDay(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    }else{
                        if (data.get("outType") != null && !StringUtils.isEmpty(data.get("outType"))) {
                            entity.setOutType("2");
                            entity.setNeedBack("0");
                        } else {
                            throw new Exception("出库类型不能为空！");
                        }
                        //预计回库时间
                        if (data.get("estimateBackDate") != null && !StringUtils.isEmpty(data.get("estimateBackDate"))) {
                            entity.setEstimateBackDate(String.valueOf(data.get("estimateBackDate")));
                        } else {
                            throw new Exception("预计回库时间不能为空！");
                        }
                    }

                    //出库打印时间
                    entity.setOutPrintDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    entity.setCreateTime(System.currentTimeMillis());
                    entity.setCreateUser(uid);
                    //出库人
                    entity.setOutStaff(uid);
                    //公司id
                    entity.setCompanyId(cid);
                    //是否出库（0未出库1已出库）
                    entity.setOutStatus("0");

                    this.itScmOutWareHouseDao.saveOrUpdate(entity);
                    if(type.equals("1")){ //销售确认出库时间
                        List ll = this.itScmOutWareHouseDao.list("select o.*,c.car_series,c.car_model,c.configure from t_scm_sale_order_detail o " +
                                "left join t_scm_car c on c.id = o.car_id where o.vin=? and o.status='0' and o.company_id=?",vin,cid);
                        if(list.size()>0){
                            Map mm = (Map) ll.get(0);
                            //保存车辆档案信息
                            saveTcrmCar(mm,uid);
                        }
                        //this.itScmOutWareHouseDao.executeSQL("update T_Scm_OutWareHouse set estimate_out_day=? where vin=? and company_id=?",new SimpleDateFormat("yyyy-MM-dd").format(new Date()),vin,TokenUtil.getCompanyId(uid));
                        //this.itScmOutWareHouseDao.executeSQL("update t_scm_car set sale_type = '2' where vin = ? and company_id=?",vin,cid);
                    }else{ //调拨确认时间
                        List l = this.itScmOutWareHouseDao.list("select t.allocation_date from t_scm_outwarehouse o left join t_scm_allocation_order_detail d " +
                                "on o.vin= d.vin left join t_scm_allocation_order t on t.id = d.allocation_order_id where o.vin=? and o.company_id=?",vin,cid);
                        Map map = (Map) l.get(0);
                        this.itScmOutWareHouseDao.executeSQL("update T_Scm_OutWareHouse set estimate_out_day=? where vin=? and company_id=?",map.get("allocationDate"),vin,cid);
                    }
                }

            }else{
                throw new Exception("请选择车辆");
            }
        }

    }

    @Override
    public List updateSerialNum(String allocationId,String uid) throws Exception{
        List<Map<String,Object>> list = this.itScmOutWareHouseDao.list("select d.*,o.allocation_type from t_scm_allocation_order_detail d" +
                " inner join t_scm_allocation_order o on o.id = d.allocation_order_id where d.allocation_order_id=?",allocationId);
        if(list.size()>0){
            for(Map<String,Object> map:list){
                String connectNo = SerialNumFactory.generateSerialNum(uid,map.get("allocationType").toString());
                this.itScmOutWareHouseDao.executeSQL("update t_scm_allocation_order_detail set connectNo = ? where allocation_order_id=? and vin = ?",connectNo,allocationId,map.get("vin"));
            }
        }
       List dataList = this.itScmOutWareHouseDao.list("select vin,connectNo from t_scm_allocation_order_detail where allocation_order_id =?",allocationId);
       return dataList;
    }

    /**
     * 保存车辆档案 信息，如存在则更新
     * zhc 此函数异常不进行抛出了，抛出了没意义 20171009
     * @param mm
     * @param uid
     * @throws Exception
     */
    private void saveTcrmCar(Map mm,String uid)  {
        try {
            String companyId = TokenUtil.getCompanyId(uid);
            String vin = StringUtil.formatEmpty(mm.get("vin"));


            if (!"".equals(vin)) {
                TCrmCar car = crmCarService.getInfoByVin(vin, companyId);
                if (car == null) {
                    StringBuffer sql = new StringBuffer();
                    List<String> params = new ArrayList<>();
                    sql.append("insert into t_crm_car(id,create_time,create_user,owner_name,owner_tel,owner_phone,company_id," +
                            " owner_identity,brand,series,model,configure,vin,buy_date,guarantee_start_date ) " +
                            " SELECT* from (select c.id scmId,c.create_time,'" + uid + "' uid,o.owen_name,o.owen_phone tel,o.owen_phone," +
                            " c.company_id,o.certificates_num,c.brand,c.car_series,c.car_model, " +
                            " c.configure,c.vin,UNIX_TIMESTAMP(DATE_FORMAT(o.invoice_date,'%Y-%m-%d'))*1000 buyDate, " +
                            " UNIX_TIMESTAMP(DATE_FORMAT(o.invoice_date,'%Y-%m-%d'))*1000 guaDate FROM t_scm_car c,  " +
                            " t_scm_sale_order o,t_scm_sale_order_detail d WHERE c.vin=? and c.company_id=? and c.id = d.car_id AND " +
                            " c.company_id = o.company_id and d.sale_order_id = o.id) scm   ");
                    params.add(StringUtil.formatEmpty(mm.get("vin")));
                    params.add(companyId);
                    this.itScmOutWareHouseDao.executeSQL(sql.toString(), params.toArray());
                } else {
                    car.setOwnerName(mm.get("invoiceHeader").toString());
                    car.setContactName(mm.get("invoiceHeader").toString());
                    if (mm.get("owenPhone") != null && !mm.get("owenPhone").equals("")) {
                        car.setOwnerPhone(mm.get("owenPhone").toString());
                        car.setOwnerTel(mm.get("owenPhone").toString());
                        car.setContactPhone(mm.get("owenPhone").toString());
                        car.setContactTel(mm.get("owenPhone").toString());
                    }
                    car.setCompanyId(mm.get("companyId").toString());
                    if (mm.get("certificatesNum") != null && mm.get("certificatesNum").equals("")) {
                        car.setOwnerIdentity(mm.get("certificatesNum").toString());
                    }
                    car.setConfigure(mm.get("configure").toString());
                    car.setModel(mm.get("carModel").toString());
                    car.setSeries(mm.get("carSeries").toString());
                    car.setVin(mm.get("vin").toString());
                    car.setOwnerIdentity(StringUtil.formatEmpty(mm.get("certificatesNum")));
                    car.setBuyDate(Long.parseLong(mm.get("createTime").toString()));
                    this.itScmOutWareHouseDao.saveOrUpdate(car);
                }
            }
            List<String> ps=new ArrayList<>();
            ps.add(StringUtil.formatEmpty(mm.get("vin")));
            ps.add(companyId);
            Map infoMap = this.itScmOutWareHouseDao.info("select * from t_insurance_car where vin=? and company_id=?",
                    ps.toArray());
            if (infoMap.size() > 0) {
                StringBuffer sql = new StringBuffer();
                List<String> params = new ArrayList<>();
                sql.append("UPDATE t_insurance_car car,(" +
                        " SELECT c.id scmId, c.company_id, c.vin, c.brand, c.car_series, c.car_series_code, c.car_series_id, " +
                        " c.car_model, c.car_model_code, c.car_model_id, c.configure, c.configure_code, c.configure_id, " +
                        " o.owen_name, o.owen_phone, o.certificates_num, o.saler, o.invoice_date FROM t_scm_car c, " +
                        " t_scm_sale_order o,t_scm_sale_order_detail d WHERE c.id = d.car_id AND c.company_id = o.company_id and d.sale_order_id = o.id) scm " +
                        " SET car.insured = scm.owen_name,  car.contact_name = scm.owen_name,  car.contact_phone = scm.owen_phone,  " +
                        " car.insured_ID_number = scm.certificates_num,  car.car_brand = scm.brand,  car.car_series = car.car_series,  " +
                        " car.car_model = car.car_model,  car.first_record_date = scm.invoice_date,  car.driver_license = scm.owen_name " +
                        " WHERE car.vin =? AND car.company_id =? and car.vin = scm.vin AND car.company_id = scm.company_id");
                params.add(StringUtil.formatEmpty(mm.get("vin")));
                params.add(companyId);
                this.itScmOutWareHouseDao.executeSQL(sql.toString(), params.toArray());
            } else {
                StringBuffer sql = new StringBuffer();
                List<String> params = new ArrayList<>();
                sql.append("insert into t_insurance_car (id, create_time, create_user, insured, insured_address," +
                        " insured_ID_number, car_age, car_brand, car_configure,car_level, car_model,  car_series, " +
                        " company_id, contact_name,contact_phone, driver_license, first_record_date, vin, saler)" +
                        " SELECT c.id ,o.create_time,'" + uid + "',o.owen_name,'' address,o.certificates_num,'1' age,c.brand," +
                        " c.configure,'2' carLevel,o.car_model_id,c.car_series,c.company_id,o.owen_name,o.owen_phone," +
                        " o.owen_name,o.invoice_date,c.vin,o.saler " +
                        " FROM " +
                        " t_scm_car c,t_scm_sale_order o,t_scm_sale_order_detail d " +
                        " WHERE c.vin=? and c.company_id=?  AND c.id = d.car_id AND c.company_id = o.company_id and d.sale_order_id = o.id");
                params.add(StringUtil.formatEmpty(mm.get("vin")));
                params.add(companyId);
                this.itScmOutWareHouseDao.executeSQL(sql.toString(), params.toArray());
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 确认出库
     * @param data
     * @throws Exception
     */
    @Override
    public String confirmOut(Map data,String uid) throws Exception {

        String cid = TokenUtil.getCompanyId(uid);
        if(this.itScmMonthlyBalanceService.ifMonthlyBalance(cid,new Date())){
            Calendar lastDate = Calendar.getInstance();
            lastDate.setTime(new Date());
            lastDate.set(Calendar.DATE, 1);
            lastDate.add(Calendar.MONTH, 1);
            lastDate.add(Calendar.DATE, -1);
            String format = new SimpleDateFormat("yyyy-MM-dd").format(lastDate.getTime());
            throw new Exception("已月结或月结中,不能出库车辆,请在"+format+"日期之后出库");
        }

            if(data.get("vin")==null||data.get("vin").equals("")){
                throw new Exception("请选择车辆");
            }
            String vin = data.get("vin").toString();
            String type = data.get("type").toString();
            //根据库存表插入入库信息记录
            if (this.itScmStockDao.list("select * from T_Scm_Stock where vin = ? and company_id=?", vin,cid).size() <= 0) {
                throw new Exception(vin+"该车辆没有库存");
            }
            //确认出库（实际出库时间）
            this.itScmOutWareHouseDao.executeSQL("update T_Scm_OutWareHouse set out_status = '1',out_date=? where vin = ? and out_status = '0' ",new SimpleDateFormat("yyyy-MM-dd").format(new Date()), vin);
            //删除库存
            this.itScmOutWareHouseDao.executeSQL("delete from T_SCM_STOCK where vin = ? and company_id=?", vin,cid);
            if (type.equals("2")&&this.itScmOutWareHouseDao.info("select * from t_scm_outwarehouse where vin = ? and out_status='1' and outtype='2'",vin).get("outType").equals("2")) { //调拨
                //目标仓库
                String aimWarehouse = this.itScmOutWareHouseDao.info("select * from t_scm_allocation_order o where EXISTS " +
                        "(select d.allocation_order_id from t_scm_allocation_order_detail d where d.vin = ? and o.id = d.allocation_order_id)",vin).get("aimWarehouse").toString();
                //目标仓库所在的公司
                String companyId = this.itScmOutWareHouseDao.info("select * from t_scm_warehouse where id =?",aimWarehouse).get("companyId").toString();
                Map map = this.itScmOutWareHouseDao.info("select * from t_scm_car where vin =?",vin);
                //移动到目标仓库(在t_scm_stock表里加入一条记录)
                TScmStock entity = new TScmStock();
                entity.setCreateTime(Calendar.getInstance().getTimeInMillis());
                entity.setAllocationStatus("0");
                if(map.get("brand")!=null&&!map.get("brand").equals("")){
                    entity.setBrand(map.get("brand").toString());
                }
                entity.setCarId(map.get("id").toString());
                entity.setCompanyId(companyId);
                //调拨进库
                entity.setEnterType("3");
                entity.setEnterDate(iCommonService.currentTime());
                entity.setVin(vin);
                entity.setWarehouseId(aimWarehouse);

                //加一条入库记录TScmEnterWareHouse
                TScmEnterWareHouse record = new TScmEnterWareHouse();
                record.setCreateUser(uid);
                record.setCreateTime(Calendar.getInstance().getTimeInMillis());
                record.setCompanyId(cid);
                record.setWarehouseId(aimWarehouse);
                record.setEnterDate(iCommonService.currentTime());
                record.setCarId(map.get("id").toString());
                record.setVin(vin);
                record.setEnterType("3");

                this.itScmOutWareHouseDao.saveOrUpdate(entity);
                this.itScmOutWareHouseDao.saveOrUpdate(record);
                return "diaobo";
            }
            if(type.equals("1")&&this.itScmOutWareHouseDao.info("select * from t_scm_outwarehouse where vin = ? and out_status = '1' and outtype='1'",vin).get("outType").equals("1")) {//销售
                this.itScmOutWareHouseDao.executeSQL("update t_scm_sale_order set out_count = out_count+1 where id in (select sale_order_id from t_scm_sale_order_detail where vin = ? and company_id=?)",vin,cid);
                return "xiaoshou";
            }
        return "fail";
    }

    /**
     * 车辆状态status(3：调拨在途 2：已售)
     * @param data
     * @param status
     */
    @Override
    public void updateCarOutStatus(Map data , String status,String uid) throws Exception{

        String cid = TokenUtil.getCompanyId(uid);
        String vin = data.get("vin").toString();

        if(status.equals("3")){//调拨
            this.itScmOutWareHouseDao.executeSQL("update t_scm_car set status = ? where vin= ? and company_id=?",status,vin,cid);
        }else{//销售
            this.itScmOutWareHouseDao.executeSQL("update t_scm_car set status = ? where vin= ? and company_id=?",status,vin,cid);
        }

    }

}
